package com.yxhl.zoume.core.specialcar.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;

import com.bigkoo.pickerview.OptionsPickerView;
import com.yxhl.zoume.R;
import com.yxhl.zoume.UIConstants;
import com.yxhl.zoume.common.ui.activity.base.BaseActivityWithToolBar;
import com.yxhl.zoume.core.specialcar.model.CarLocationMapEntrance;
import com.yxhl.zoume.core.specialcar.model.SpecialCarContainerEntrance;
import com.yxhl.zoume.core.specialcar.model.SpecialCarContainerActivityParam;
import com.yxhl.zoume.core.specialcar.fragment.SpecialCarHomeFragment;
import com.yxhl.zoume.core.specialcar.fragment.SpecialCarLocationMapFragment;
import com.yxhl.zoume.core.specialcar.fragment.SpecialCarPOISearchFragment;
import com.yxhl.zoume.core.main.info.HeaderOperationType;
import com.yxhl.zoume.utils.timepicker.TimePickerHelper;

import java.util.List;

import butterknife.BindView;

/**
 * created by sugarya 16/08/14
 * 承载Fragment的容器,扮演Fragment管理者
 */
public class SpecialCarContainerActivity extends BaseActivityWithToolBar {

    public static final String FRAGMENT_SPECIAL_CAR_HOME = "SpecialCarHomeFragment";
    public static final String FRAGMENT_CAR_LOCATION_MAP = "SpecialCarLocationMapFragment";
    public static final String FRAGMENT_CAR_POI_SEARCH = "CarPOISearchFragment";
    public static final String FRAGMENT_SELECT_CITY = "selectCityFragment";
    private static final String TAG = "SpecialCarContainerAct";
    private static final String YI_YANG_CITY = "益阳市";

    @BindView(R.id.special_car_activity_content)
    FrameLayout mContentFrame;

    /**
     * 传递过来的参数
     */
    private SpecialCarContainerActivityParam mActivityParam;

    /**
     * 用户选择的城市
     */
    private String mUserSelectCity = YI_YANG_CITY;


    private String mCurrentShowFragmentTab;


    public static Intent getCallingIntent(Activity activity, SpecialCarContainerActivityParam activityParam) {
        Intent intent = new Intent(activity, SpecialCarContainerActivity.class);
        intent.putExtra(UIConstants.Car.INTENT_KEY_SPECIAL_CAR_CONTAINER_PARAM, activityParam);
        return intent;
    }

    private void handleIntent() {
        Intent intent = getIntent();
        if (intent != null) {
            mActivityParam = (SpecialCarContainerActivityParam) intent.getSerializableExtra(UIConstants.Car.INTENT_KEY_SPECIAL_CAR_CONTAINER_PARAM);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        handleIntent();
        initializeDisplay();
    }

    /**
     * 初始化显示快车页面
     */
    private void initializeDisplay() {
        if (mActivityParam != null) {
            SpecialCarContainerEntrance containerEntrance = mActivityParam.getContainerEntrance();
            String orderId = mActivityParam.getSpecialCarOrderId();
            if (containerEntrance != null) {
                switch (containerEntrance) {
                    case SCHEDULE_MAP_FROM_PUSH:
                        if (!TextUtils.isEmpty(orderId)) {
                            getAppComponent().navigator().navigateToSpecialCarScheduleActivity(this, orderId);
                        }
                        break;
                    case SPECIAL_CAR_HOME:
                        displayOneFragment(FRAGMENT_SPECIAL_CAR_HOME, CarLocationMapEntrance.DEFAULT);
                        break;
                }
            }
        }
    }

    /**
     * 跳转到出发地点地图
     */
    public void navigateDepartStationMap() {
        displayOneFragment(FRAGMENT_CAR_LOCATION_MAP, CarLocationMapEntrance.SPECIAL_CAR_START);
    }

    /**
     * 跳转到到达地点地图
     */
    public void navigateArrivalStationMap() {
        displayOneFragment(FRAGMENT_CAR_LOCATION_MAP, CarLocationMapEntrance.SPECIAL_CAR_ARRIVAL);
    }

    /**
     * 显示特定Tag的Fragment
     *
     * @param fragmentTab
     */
    public void showOneFragmentOnBackPressed(String fragmentTab) {
        FragmentManager manager = getSupportFragmentManager();
        if (manager != null) {
            List<Fragment> fragments = manager.getFragments();
            FragmentTransaction transaction = manager.beginTransaction();
            for (Fragment f : fragments) {
                if (f.getClass().getSimpleName().equals(fragmentTab)) {
                    transaction.show(f);
                } else {
                    transaction.hide(f);
                }
            }
            transaction.commitAllowingStateLoss();
        }
    }

    /**
     * 显示特定Tag的Fragment,如果是第一次,则新建并添加
     *
     * @param fragmentTab
     */
    public void displayOneFragment(String fragmentTab, CarLocationMapEntrance entrance) {
        FragmentManager manager = getSupportFragmentManager();
        if (manager != null) {
            FragmentTransaction transaction = manager.beginTransaction();

            List<Fragment> fragments = manager.getFragments();
            if (fragments != null && fragments.size() > 0) {
                for (Fragment f : fragments) {
                    if (f != null) {
                        transaction.hide(f);
                    }
                }
            }

            Fragment fragmentByTag = manager.findFragmentByTag(fragmentTab);
            if (fragmentByTag != null) {
                if (fragmentByTag instanceof SpecialCarLocationMapFragment) {
                    SpecialCarLocationMapFragment locationMapFragment = (SpecialCarLocationMapFragment) fragmentByTag;
                    locationMapFragment.setEntrance(entrance);
                } else if (fragmentByTag instanceof SpecialCarPOISearchFragment) {
                    SpecialCarPOISearchFragment poiSearchFragment = (SpecialCarPOISearchFragment) fragmentByTag;
                    poiSearchFragment.setEntrance(entrance);
                }
                transaction.show(fragmentByTag);
            } else {
                transaction.add(R.id.special_car_activity_content, fragmentProvider(fragmentTab, entrance), fragmentTab);
            }

            transaction.commitAllowingStateLoss();
            mCurrentShowFragmentTab = fragmentTab;
        }
    }

    /**
     * Fragment提供者
     *
     * @param fragmentTag
     * @param entrance
     * @return
     */
    private Fragment fragmentProvider(String fragmentTag, CarLocationMapEntrance entrance) {
        switch (fragmentTag) {
            case FRAGMENT_SPECIAL_CAR_HOME:
                return SpecialCarHomeFragment.newInstance();

            case FRAGMENT_CAR_LOCATION_MAP:
                switch (entrance) {
                    case SPECIAL_CAR_START:
                        return SpecialCarLocationMapFragment.newInstance(CarLocationMapEntrance.SPECIAL_CAR_START);
                    case SPECIAL_CAR_ARRIVAL:
                        return SpecialCarLocationMapFragment.newInstance(CarLocationMapEntrance.SPECIAL_CAR_ARRIVAL);
                    default:
                        return SpecialCarLocationMapFragment.newInstance(CarLocationMapEntrance.SPECIAL_CAR_START);
                }

            case FRAGMENT_CAR_POI_SEARCH:
                return SpecialCarPOISearchFragment.newInstance(entrance);

            default:
                return SpecialCarHomeFragment.newInstance();
        }
    }


    /**
     * 当按系统回退键时,如果快车的时间选择器正在显示,则关闭之
     */
    @Override
    public void onBackPressed() {
        if (closeOptionsPickerView()) {
            switch (mCurrentShowFragmentTab) {
                case FRAGMENT_SPECIAL_CAR_HOME:
                    super.onBackPressed();
                    break;
                case FRAGMENT_CAR_LOCATION_MAP:
                    mCurrentShowFragmentTab = SpecialCarHomeFragment.class.getSimpleName();
                    showOneFragmentOnBackPressed(mCurrentShowFragmentTab);
                    break;
                case FRAGMENT_CAR_POI_SEARCH:
                    mCurrentShowFragmentTab = SpecialCarLocationMapFragment.class.getSimpleName();
                    SpecialCarLocationMapFragment locationMapFragment =
                            (SpecialCarLocationMapFragment) getSupportFragmentManager()
                                    .findFragmentByTag(mCurrentShowFragmentTab);
                    locationMapFragment.setFromPOISearchFragment(true);
                    showOneFragmentOnBackPressed(mCurrentShowFragmentTab);
                    break;
                default:
                    super.onBackPressed();
            }
        }
    }

    /**
     * 关闭出行时间选择器
     *
     * @return
     */
    private boolean closeOptionsPickerView() {
        OptionsPickerView<String> optionsPickerView = TimePickerHelper.newInstance(this).getOptionsPickerView();
        if (optionsPickerView != null) {
            boolean showing = optionsPickerView.isShowing();
            if (showing) {
                optionsPickerView.dismiss();
                return false;
            }
        }
        return true;
    }


    public String getUserSelectCity() {
        return mUserSelectCity;
    }

    public void setUserSelectCity(String mSelectCity) {
        this.mUserSelectCity = mSelectCity;
    }


    @Override
    protected void onHeaderLeftClick(View view) {
        onBackPressed();
    }

    @Override
    protected void onHeaderRightClick(View view) {
        if (view != null) {
            HeaderOperationType operationType = (HeaderOperationType) view.getTag();
            switch (operationType) {
                case PASSENGER_NOCIE:
                    getAppComponent().navigator().navigateToPassengerNoticeActivity(this);
                    break;
            }
        }
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_special_car_container;
    }

    @Override
    protected void initializeInjector() {

    }

}
